package cn.gson.financial.kernel.service.impl;

import cn.gson.financial.kernel.common.DateUtil;
import cn.gson.financial.kernel.common.DoubleValueUtil;
import cn.gson.financial.kernel.model.entity.*;
import cn.gson.financial.kernel.model.mapper.*;
import cn.gson.financial.kernel.model.vo.IndexTargetVo;
import cn.gson.financial.kernel.model.vo.ReportDataVo;
import cn.gson.financial.kernel.model.vo.VoucherDetailVo;
import cn.gson.financial.kernel.service.ReportTemplateService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportTemplateServiceImpl extends ServiceImpl<ReportTemplateMapper, ReportTemplate> implements ReportTemplateService {

    @Autowired
    private ReportTemplateItemsMapper itemsMapper;

    @Autowired
    private ReportTemplateItemsFormulaMapper formulaMapper;

    @Autowired
    private VoucherMapper voucherMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private AccountSetsMapper accountSetsMapper;
    @Autowired
    private AllSelectMapper allSelectMapper;

    private DateFormat sdf = new SimpleDateFormat("yyyy");

    @Override
    public int batchInsert(List<ReportTemplate> list) {
        return baseMapper.batchInsert(list);
    }


    /**
     * 计算报表
     *
     * @param accountSetsId
     * @param id
     * @param accountDate
     * @return
     */
    @Override
    public Map<Integer, ReportDataVo> view(Integer accountSetsId, Long id, Date accountDate) {
        AccountSets accountSets = accountSetsMapper.selectById(accountSetsId);

        LambdaQueryWrapper<ReportTemplate> qw = Wrappers.lambdaQuery();
        qw.eq(ReportTemplate::getAccountSetsId, accountSetsId);
        qw.eq(ReportTemplate::getId, id);
        ReportTemplate template = this.getOne(qw);
        log.info("{}", template);
        Map<Integer, ReportDataVo> dataVoMap = new HashMap<>();
        if (template.getItems() != null) {
            //先计算表外公式
            template.getItems().stream().filter(rti -> rti.getSources() == 0 && !rti.getIsClassified()).forEach(item -> {
                ReportDataVo dataVo = new ReportDataVo();
                dataVo.setItemId(item.getId());

                //获取计算项
                if (item.getFormulas() != null && !item.getFormulas().isEmpty()) {
                    //所有计算项目的科目 id
                    List<String> fromTags = item.getFormulas().stream().map(ReportTemplateItemsFormula::getFromTag).collect(Collectors.toList());
                    List<Subject> subjectList = subjectMapper.selectBatchIds(fromTags);
                    Map<Integer, Subject> subjectMap = subjectList.stream().collect(Collectors.toMap(Subject::getId, subject -> subject));
                    List<String> codes = subjectList.stream().map(Subject::getCode).collect(Collectors.toList());

                    List<VoucherDetailVo> detailVos;

                    if (template.getType() == 0) {
                        //各科目的期年统计数据
                        detailVos = voucherMapper.selectReportStatistical(accountSetsId, codes, DateUtil.getMonthEnd(accountDate));
                    } else {
                        //资产负债查余额
                        detailVos = voucherMapper.selectReportBalanceStatistical(accountSetsId, codes, DateUtil.getMonthEnd(accountDate));
                    }


                    //先根据期年进行分组，再根据科目 id 进行数据转换
                    Map<String, Map<String, VoucherDetailVo>> collect = detailVos.stream().collect(Collectors.groupingBy(VoucherDetailVo::getSummary, Collectors.toMap(VoucherDetailVo::getSubjectCode, vo -> vo)));

                    Map<String, VoucherDetailVo> periodData = collect.get("本期");
                    Map<String, VoucherDetailVo> yearData = collect.get("本年");

                    //如果本年余额为空
                    if ((yearData.isEmpty() || yearData.values().stream().allMatch(vo -> vo.isNull())) && template.getType() == 1 && sdf.format(accountSets.getEnableDate()).equals(sdf.format(accountDate))) {
                        List<VoucherDetailVo> detailInitVos = voucherMapper.selectReportInitBalance(accountSetsId, codes);
                        yearData = detailInitVos.stream().collect(Collectors.groupingBy(VoucherDetailVo::getSummary, Collectors.toMap(VoucherDetailVo::getSubjectCode, vo -> vo))).get("本年");
                    }

                    //计算公式合计
                    dataVo.setCurrentPeriodAmount(getaCombined(subjectMap, item, periodData));
                    dataVo.setCurrentYearAmount(getaCombined(subjectMap, item, yearData));
                }

                dataVoMap.put(item.getId(), dataVo);
            });

            //表内
            template.getItems().stream().filter(rti -> rti.getSources() == 1 && !rti.getIsClassified()).forEach(item -> {
                ReportDataVo dataVo = new ReportDataVo();
                dataVo.setItemId(item.getId());
                Double periodNum = null;
                Double yearNum = null;
                if (item.getFormulas() != null && !item.getFormulas().isEmpty()) {
                    for (ReportTemplateItemsFormula formula : item.getFormulas()) {
                        //获取表内已计算的
                        ReportDataVo dataVo1 = dataVoMap.get(Integer.parseInt(formula.getFromTag()));
                        if (dataVo1 != null) {
                            if (periodNum == null) {
                                periodNum = dataVo1.getCurrentPeriodAmount();
                            } else {
                                switch (formula.getCalculation().toString()) {
                                    case "+":
                                        periodNum += DoubleValueUtil.getNotNullVal(dataVo1.getCurrentPeriodAmount());
                                        break;
                                    case "-":
                                        periodNum -= DoubleValueUtil.getNotNullVal(dataVo1.getCurrentPeriodAmount());
                                        break;
                                }
                            }

                            if (yearNum == null) {
                                yearNum = dataVo1.getCurrentYearAmount();
                            } else {
                                switch (formula.getCalculation().toString()) {
                                    case "+":
                                        yearNum += DoubleValueUtil.getNotNullVal(dataVo1.getCurrentYearAmount());
                                        break;
                                    case "-":
                                        yearNum -= DoubleValueUtil.getNotNullVal(dataVo1.getCurrentYearAmount());
                                        break;
                                }
                            }
                        }
                    }
                }
                dataVo.setCurrentPeriodAmount(periodNum);
                dataVo.setCurrentYearAmount(yearNum);
                dataVoMap.put(item.getId(), dataVo);
            });
        }
        return dataVoMap;
    }



    /**
     * 计算报表改版  -动态
     *
     * @param accountSetsId
     * @param id
     * @param
     * @return
     */
    @Override
    public Map<Integer, ReportDataVo> viewReport(Integer accountSetsId, Long id, String sTime,String eTime) {
        System.out.println(accountSetsId+"----"+id+"----"+sTime+"----"+eTime);
        Date date1 = new Date();
        try {
            date1 = new SimpleDateFormat("yyyy-MM-dd").parse(sTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String date = sdf.format(date1);
        System.out.println("格式化日期: " + sdf.format(date1));
        AccountSets accountSets = accountSetsMapper.selectById(accountSetsId);

        LambdaQueryWrapper<ReportTemplate> qw = Wrappers.lambdaQuery();
        qw.eq(ReportTemplate::getAccountSetsId, accountSetsId);
        qw.eq(ReportTemplate::getId, id);
        ReportTemplate template = this.getOne(qw);
        log.info("{}", template);
        Map<Integer, ReportDataVo> dataVoMap = new HashMap<>();
        if (template.getItems() != null) {
            //先计算表外公式
            template.getItems().stream().filter(rti -> rti.getSources() == 0 && !rti.getIsClassified()).forEach(item -> {
                ReportDataVo dataVo = new ReportDataVo();
                dataVo.setItemId(item.getId());

                //获取计算项
                if (item.getFormulas() != null && !item.getFormulas().isEmpty()) {
                    //所有计算项目的科目 id
                    List<String> fromTags = item.getFormulas().stream().map(ReportTemplateItemsFormula::getFromTag).collect(Collectors.toList());
                    List<Subject> subjectList = subjectMapper.selectBatchIds(fromTags);
                    Map<Integer, Subject> subjectMap = subjectList.stream().collect(Collectors.toMap(Subject::getId, subject -> subject));
                    List<String> codes = subjectList.stream().map(Subject::getCode).collect(Collectors.toList());

                    List<VoucherDetailVo> detailVos;

                    if (template.getType() == 0) {
                        //各科目的期年统计数据
                        detailVos = voucherMapper.selectReportStatisticalByParam(accountSetsId, codes,sTime,eTime);
                        if (detailVos.size()!=0){
                            for (int i = 0; i < detailVos.size(); i++) {
                                detailVos.get(i).setBalanceDirection(voucherMapper.selectBalanceDirection(detailVos.get(i).getSubjectCode(),accountSetsId));
                                if (detailVos.get(i).getSummary().equals("本季")){
                                    if (detailVos.get(i).getBalanceDirection().equals("借")){
                                        detailVos.get(i).setDebitAmount(DoubleValueUtil.getNotNullVal(detailVos.get(i).getDebitAmount())+DoubleValueUtil.getNotNullVal(voucherMapper.selectInitYearAmount(accountSetsId,detailVos.get(i).getSubjectCode())));
                                    }else {
                                        detailVos.get(i).setCreditAmount(DoubleValueUtil.getNotNullVal(detailVos.get(i).getCreditAmount())+DoubleValueUtil.getNotNullVal(detailVos.get(i).getCumulativeCredit()));
                                    }
                                }
                            }
                        }
                    } else {
                        //资产负债查余额
                        detailVos = voucherMapper.selectReportBalanceStatisticalByParam(accountSetsId, codes,sTime,eTime);
                    }
                    //查期初
                    List<VoucherDetailVo> detailInitVos = voucherMapper.selectReportInitBalance(accountSetsId, codes);
                    //查本年发生额
                    System.out.println(codes);
                    List<VoucherDetailVo> yearAmount = voucherMapper.selectyearAmount(accountSetsId, codes);
                    System.out.println(yearAmount);
                    double init = 0d;
                    double incurredAmount = 0d;
                    if (detailInitVos.size()!=0){
                        for (int i = 0; i <detailInitVos.size() ; i++) {
                            init=init+DoubleValueUtil.getNotNullVal(detailInitVos.get(i).getDebitAmount());
                        }
                    }
                    if (yearAmount.size()!=0){
                        for (int i = 0; i <yearAmount.size() ; i++) {
                            double incurredAmountParm = 0d;
                            if (yearAmount.get(i).getBalanceDirection() == null){
                                break;
                            }
                            String balanceDirection = voucherMapper.selectBalanceDirection(yearAmount.get(i).getSubjectCode(),accountSetsId);
                            if (balanceDirection.equals("贷")){
                                incurredAmountParm=DoubleValueUtil.getNotNullVal(yearAmount.get(i).getCumulativeCredit())
                                        -DoubleValueUtil.getNotNullVal(yearAmount.get(i).getCumulativeDebit());
                            }else {
                                incurredAmountParm=DoubleValueUtil.getNotNullVal(yearAmount.get(i).getCumulativeDebit())
                                        -DoubleValueUtil.getNotNullVal(yearAmount.get(i).getCumulativeCredit());
                            }
                            System.out.println(incurredAmountParm);
                            incurredAmount=incurredAmount+incurredAmountParm;
                        }
                    }
                    System.out.println(incurredAmount);

                    //先根据期年进行分组，再根据科目 id 进行数据转换
                    Map<String, Map<String, VoucherDetailVo>> collect = detailVos.stream().collect(Collectors.groupingBy(VoucherDetailVo::getSummary, Collectors.toMap(VoucherDetailVo::getSubjectCode, vo -> vo)));

                    Map<String, VoucherDetailVo> periodData = collect.get("本期");
                    Map<String, VoucherDetailVo> yearData = collect.get("本季");
                    System.out.println("本期"+periodData);
                    System.out.println("本年"+yearData);
                    //年初余额：
                    //如果本年余额为空，说明今年以前没有数据，年初=期初
                    if (yearData==null && template.getType() == 1 && sdf.format(accountSets.getEnableDate()).equals(date)) {
//                        yearData = detailInitVos.stream().collect(Collectors.groupingBy(VoucherDetailVo::getSummary, Collectors.toMap(VoucherDetailVo::getSubjectCode, vo -> vo))).get("本季");
                        dataVo.setCurrentYearAmount(init);

                    }else {
                        //年前不为空，年初=期初-年前所有
                        if (template.getType() == 1&&init==0d){
                            dataVo.setCurrentYearAmount(getaCombined(subjectMap, item, yearData));
                        }
                        if(template.getType() == 1&&init!=0d){
                            dataVo.setCurrentYearAmount(init+getaCombined(subjectMap, item, yearData));
                        }
                    }

                    //计算公式合计
                    if (dataVo.getCurrentYearAmount()!=null&&template.getType() == 1){
                        dataVo.setCurrentPeriodAmount(dataVo.getCurrentYearAmount()+getaCombined(subjectMap, item, periodData)+DoubleValueUtil.getNotNullVal(incurredAmount));
                    }else {
                        dataVo.setCurrentPeriodAmount(getaCombined(subjectMap, item, periodData));
                        dataVo.setCurrentYearAmount(getaCombined(subjectMap, item, yearData));
                    }

//
                }

                dataVoMap.put(item.getId(), dataVo);
            });

            //表内
            template.getItems().stream().filter(rti -> rti.getSources() == 1 && !rti.getIsClassified()).forEach(item -> {
                ReportDataVo dataVo = new ReportDataVo();
                dataVo.setItemId(item.getId());
                Double periodNum = null;
                Double yearNum = null;
                if (item.getFormulas() != null && !item.getFormulas().isEmpty()) {
                    for (ReportTemplateItemsFormula formula : item.getFormulas()) {
                        //获取表内已计算的
                        ReportDataVo dataVo1 = dataVoMap.get(Integer.parseInt(formula.getFromTag()));
                        if (dataVo1 != null) {
                            if (periodNum == null) {
                                periodNum = dataVo1.getCurrentPeriodAmount();
                            } else {
                                switch (formula.getCalculation().toString()) {
                                    case "+":
                                        periodNum += DoubleValueUtil.getNotNullVal(dataVo1.getCurrentPeriodAmount());
                                        break;
                                    case "-":
                                        periodNum -= DoubleValueUtil.getNotNullVal(dataVo1.getCurrentPeriodAmount());
                                        break;
                                }
                            }

                            if (yearNum == null) {
                                yearNum = dataVo1.getCurrentYearAmount();
                            } else {
                                switch (formula.getCalculation().toString()) {
                                    case "+":
                                        yearNum += DoubleValueUtil.getNotNullVal(dataVo1.getCurrentYearAmount());
                                        break;
                                    case "-":
                                        yearNum -= DoubleValueUtil.getNotNullVal(dataVo1.getCurrentYearAmount());
                                        break;
                                }
                            }
                        }
                    }
                }
                dataVo.setCurrentPeriodAmount(periodNum);
                dataVo.setCurrentYearAmount(yearNum);
                dataVoMap.put(item.getId(), dataVo);
            });
        }
        //看平不平
        if (template.getTemplateKey().equals("zcfzb")){
            ReportDataVo dataVoPing = new ReportDataVo();
            List<ReportTemplateItems> zclist = allSelectMapper.selectReportTemplateItemsById(template.getId());
            Integer a1=0;
            Integer a2=0;
            for (int i = 0; i < zclist.size(); i++) {
                if (zclist.get(i).getTitle().equals("资产合计") || zclist.get(i).getTitle().equals("资产总计")){
                    a1 = zclist.get(i).getId();
                }
                if (zclist.get(i).getTitle().equals("负债和所有者权益（或股东权益）合计") || zclist.get(i).getTitle().equals("负债和所有者权益（或股东权益）总计")){
                    a2 = zclist.get(i).getId();
                }
            }
//            System.out.println(a1+""+a2);
            dataVoPing.setItemId(0);
            dataVoPing.setCurrentYearAmount(DoubleValueUtil.getNotNullVal(dataVoMap.get(a1).getCurrentPeriodAmount()));
            dataVoPing.setCurrentPeriodAmount(DoubleValueUtil.getNotNullVal(dataVoMap.get(a2).getCurrentPeriodAmount()));
            dataVoMap.put(0,dataVoPing);
        }
        return dataVoMap;
    }







    /**
     * 计算 部门 项目报表
     *
     * @return
     */
    @Override
    public Map<Integer, ReportDataVo> view2(Integer accountSetsId,Long reportTemlateId,String sTime,String eTime,Integer bmxmId) {
        AccountSets accountSets = accountSetsMapper.selectById(accountSetsId);

        LambdaQueryWrapper<ReportTemplate> qw = Wrappers.lambdaQuery();
        qw.eq(ReportTemplate::getAccountSetsId, accountSetsId);
        qw.eq(ReportTemplate::getId, reportTemlateId);
        ReportTemplate template = this.getOne(qw);
        log.info("{}", template);
        Map<Integer, ReportDataVo> dataVoMap = new HashMap<>();
        if (template.getItems() != null) {
            //先计算表外公式
            template.getItems().stream().filter(rti -> rti.getSources() == 0 && !rti.getIsClassified()).forEach(item -> {
                ReportDataVo dataVo = new ReportDataVo();
                dataVo.setItemId(item.getId());

                //获取计算项
                if (item.getFormulas() != null && !item.getFormulas().isEmpty()) {
                    //所有计算项目的科目 id
                    List<String> fromTags = item.getFormulas().stream().map(ReportTemplateItemsFormula::getFromTag).collect(Collectors.toList());
                    List<Subject> subjectList = subjectMapper.selectBatchIds(fromTags);
//                    for (Subject subject : subjectList) {
//                        System.out.println("subject: " + subject);
//                    }
                    Map<Integer, Subject> subjectMap = subjectList.stream().collect(Collectors.toMap(Subject::getId, subject -> subject));
                    List<String> codes = subjectList.stream().map(Subject::getCode).collect(Collectors.toList());

                    List<VoucherDetailVo> detailVos=new ArrayList<>();

                    if (template.getType() == 0) {
                        //各科目的期年统计数据
                        detailVos = voucherMapper.selectReportStatistical2(accountSetsId,codes,sTime,eTime,bmxmId);
                    } else {
                        //资产负债查余额
//                        detailVos = voucherMapper.selectReportBalanceStatistical(accountSetsId, codes, DateUtil.getMonthEnd(accountDate));
                        //利润表 不需要查询 负债
                        detailVos = null;
                    }

                    System.out.println("detailVos: " + detailVos);
                    //先根据期年进行分组，再根据科目 id 进行数据转换
                    Map<String, Map<String, VoucherDetailVo>> collect = detailVos.stream().collect(Collectors.groupingBy(VoucherDetailVo::getSummary, Collectors.toMap(VoucherDetailVo::getSubjectCode, vo -> vo)));

                    Map<String, VoucherDetailVo> periodData = collect.get("本期");
                    Map<String, VoucherDetailVo> yearData = collect.get("本季度");

                    //如果本季余额为空
                    if ((yearData.isEmpty() || yearData.values().stream().allMatch(vo -> vo.isNull())) && template.getType() == 1 && sdf.format(accountSets.getEnableDate()).equals(sdf.format(eTime))) {
                        List<VoucherDetailVo> detailInitVos = voucherMapper.selectReportInitBalance(accountSetsId, codes);
                        yearData = detailInitVos.stream().collect(Collectors.groupingBy(VoucherDetailVo::getSummary, Collectors.toMap(VoucherDetailVo::getSubjectCode, vo -> vo))).get("本季");
                    }

                    //计算公式合计
                    dataVo.setCurrentPeriodAmount(getaCombined(subjectMap, item, periodData));
                    dataVo.setCurrentYearAmount(getaCombined(subjectMap, item, yearData));
                }

                dataVoMap.put(item.getId(), dataVo);
            });

            //表内
            template.getItems().stream().filter(rti -> rti.getSources() == 1 && !rti.getIsClassified()).forEach(item -> {
                ReportDataVo dataVo = new ReportDataVo();
                dataVo.setItemId(item.getId());
                Double periodNum = null;
                Double yearNum = null;
                if (item.getFormulas() != null && !item.getFormulas().isEmpty()) {
                    for (ReportTemplateItemsFormula formula : item.getFormulas()) {
                        //获取表内已计算的
                        ReportDataVo dataVo1 = dataVoMap.get(Integer.parseInt(formula.getFromTag()));
                        if (dataVo1 != null) {
                            if (periodNum == null) {
                                periodNum = dataVo1.getCurrentPeriodAmount();
                            } else {
                                switch (formula.getCalculation().toString()) {
                                    case "+":
                                        periodNum += DoubleValueUtil.getNotNullVal(dataVo1.getCurrentPeriodAmount());
                                        break;
                                    case "-":
                                        periodNum -= DoubleValueUtil.getNotNullVal(dataVo1.getCurrentPeriodAmount());
                                        break;
                                }
                            }

                            if (yearNum == null) {
                                yearNum = dataVo1.getCurrentYearAmount();
                            } else {
                                switch (formula.getCalculation().toString()) {
                                    case "+":
                                        yearNum += DoubleValueUtil.getNotNullVal(dataVo1.getCurrentYearAmount());
                                        break;
                                    case "-":
                                        yearNum -= DoubleValueUtil.getNotNullVal(dataVo1.getCurrentYearAmount());
                                        break;
                                }
                            }
                        }
                    }
                }
                dataVo.setCurrentPeriodAmount(periodNum);
                dataVo.setCurrentYearAmount(yearNum);
                dataVoMap.put(item.getId(), dataVo);
            });
        }
        return dataVoMap;
    }



    /**
     * 根据工具合计
     *
     * @param item
     * @param periodData
     * @return
     */
    private Double getaCombined(Map<Integer, Subject> codes, ReportTemplateItems item, Map<String, VoucherDetailVo> periodData) {
        double periodNum = 0d;
        if (periodData == null) {
            return periodNum;
        }
        //计算本期合计
        for (ReportTemplateItemsFormula formula : item.getFormulas()) {
            Subject subject = codes.get(Integer.parseInt(formula.getFromTag()));
            VoucherDetailVo vo = periodData.get(subject.getCode());
            if (vo != null) {
                //0: " 净发生额", 1: "借方发生额", 2: "贷方发生额", 3: "余额", 4: "期末余额", 5: "期初余额"
                double money = 0;
                switch (formula.getAccessRules()) {
                    case 0://净发生额
                    case 3://余额
                        switch (subject.getBalanceDirection() + "") {
                            case "借":
                                money = DoubleValueUtil.getNotNullVal(vo.getDebitAmount()) - DoubleValueUtil.getNotNullVal(vo.getCreditAmount());
                                break;
                            case "贷":
                                money = DoubleValueUtil.getNotNullVal(vo.getCreditAmount()) - DoubleValueUtil.getNotNullVal(vo.getDebitAmount());
                                break;
                        }
                        break;
                    case 1://借方发生额
                        money = DoubleValueUtil.getNotNullVal(vo.getDebitAmount());
                        break;
                    case 2://贷方发生额
                        money = DoubleValueUtil.getNotNullVal(vo.getCreditAmount());
                        break;
                    case 4://借方余额
                        money = DoubleValueUtil.getNotNullVal(vo.getDebitAmount()) - DoubleValueUtil.getNotNullVal(vo.getCreditAmount());
                        break;
                    case 5://贷方余额
                        money = DoubleValueUtil.getNotNullVal(vo.getCreditAmount()) - DoubleValueUtil.getNotNullVal(vo.getDebitAmount());
                        break;
                }

                //计算公式
                switch (formula.getCalculation().toString()) {
                    case "+":
                        periodNum += money;
                        break;
                    case "-":
                        periodNum -= money;
                        break;
                }
            }
        }
        return periodNum;
    }

    @Override
    public ReportTemplate getOne(Wrapper<ReportTemplate> queryWrapper) {
        ReportTemplate template = baseMapper.selectOne(queryWrapper);
        LambdaQueryWrapper<ReportTemplateItems> rtiQw = Wrappers.lambdaQuery();
        rtiQw.orderByAsc(ReportTemplateItems::getPos);
        rtiQw.eq(ReportTemplateItems::getTemplateId, template.getId());
        template.setItems(itemsMapper.selectList(rtiQw));

        template.getItems().forEach(it -> {
            LambdaQueryWrapper<ReportTemplateItemsFormula> rtifQw = Wrappers.lambdaQuery();
            rtifQw.eq(ReportTemplateItemsFormula::getTemplateItemsId, it.getId());
            it.setFormulas(formulaMapper.selectList(rtifQw));
        });

        return template;
    }
    @Override
    public List<IndexTargetVo> IndexTarget(Integer accountSetsId, String timeStart, String timeEnd) {

        Integer lrId = allSelectMapper.selectLirunReport(accountSetsId,"利润表");
        Integer zcId = allSelectMapper.selectLirunReport(accountSetsId,"资产负债表");

        List<ReportTemplateItems> lrlist = allSelectMapper.selectReportTemplateItemsById(lrId);
        List<ReportTemplateItems> zclist = allSelectMapper.selectReportTemplateItemsById(zcId);
        Long lrIdLong = new Long((long)lrId);
        Map<Integer, ReportDataVo> lrMap = viewReport(accountSetsId,lrIdLong,timeStart,timeEnd);
        Long zcIdLong = new Long((long)zcId);
        Map<Integer, ReportDataVo> zcMap = viewReport(accountSetsId,zcIdLong,timeStart,timeEnd);
        Integer a1=0;
        Integer a2=0;
        Integer a3=0;
        Integer a4=0;
        Integer a5=0;
        Integer a6=0;
        Integer a7=0;
        Integer a8=0;
        for (int i = 0; i < zclist.size(); i++) {
            if (zclist.get(i).getTitle().equals("货币资金")){
                a1 = zclist.get(i).getId();
            }
            if (zclist.get(i).getTitle().equals("应收账款")){
                a2 = zclist.get(i).getId();
            }
            if (zclist.get(i).getTitle().equals("存货")){
                a3 = zclist.get(i).getId();
            }
            if (zclist.get(i).getTitle().equals("固定资产")||zclist.get(i).getTitle().equals("固定资产账面价值")){
                a4 = zclist.get(i).getId();
            }
            if (zclist.get(i).getTitle().equals("应付账款")){
                a5 = zclist.get(i).getId();
            }
            if (zclist.get(i).getTitle().equals("应交税费")){
                a6 = zclist.get(i).getId();
            }
        }
        for (int i = 0; i < lrlist.size(); i++) {
            if (lrlist.get(i).getTitle().equals("一、营业收入")){
                a7 = lrlist.get(i).getId();
            }
            if (lrlist.get(i).getTitle().equals("三、利润总额（亏损失以“-”号填列）")){
                a8 = lrlist.get(i).getId();
            }
        }
        List<IndexTargetVo> list = new ArrayList<>();
        if (zcMap.get(a1).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo1= new IndexTargetVo();
            vo1.setTarget(zcMap.get(a1).getCurrentPeriodAmount());
            vo1.setName("货币资金");
            list.add(vo1);
        }
        if (zcMap.get(a2).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo2= new IndexTargetVo();
            vo2.setTarget(zcMap.get(a2).getCurrentPeriodAmount());
            vo2.setName("应收账款");
            list.add(vo2);
        }
        if (zcMap.get(a3).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo3= new IndexTargetVo();
            vo3.setTarget(zcMap.get(a3).getCurrentPeriodAmount());
            vo3.setName("存货");
            list.add(vo3);
        }
        if (zcMap.get(a4).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo4= new IndexTargetVo();
            vo4.setTarget(zcMap.get(a4).getCurrentPeriodAmount());
            vo4.setName("固定资产");
            list.add(vo4);
        }
        if (zcMap.get(a5).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo5= new IndexTargetVo();
            vo5.setTarget(zcMap.get(a5).getCurrentPeriodAmount());
            vo5.setName("应付账款");
            list.add(vo5);
        }
        if (zcMap.get(a6).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo6= new IndexTargetVo();
            vo6.setTarget(zcMap.get(a6).getCurrentPeriodAmount());
            vo6.setName("应交税费");
            list.add(vo6);
        }
        if (lrMap.get(a7).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo7= new IndexTargetVo();
            vo7.setTarget(lrMap.get(a7).getCurrentPeriodAmount());
            vo7.setName("营业收入");
            list.add(vo7);
        }
        if (lrMap.get(a8).getCurrentPeriodAmount()!=null){
            IndexTargetVo vo8= new IndexTargetVo();
            vo8.setTarget(lrMap.get(a8).getCurrentPeriodAmount());
            vo8.setName("利润总额");
            list.add(vo8);
        }
        return list;
    }
}
